var good_size = [
			[11, 9, 9],	 // 纸箱
			[12, 10, 10],  // 木箱
			[10, 7, 7]  // 托盘
		]	// 几种预设货物的尺寸
var good_weight = [200, 600, 300]
		
var editTr = null;

var config_dict = {};  // 配置项参数(参数值来自配置界面)

var all_routes = null;


var closeModel = function() {
	$('#edit-modal').removeClass('show');
	$('#edit-modal').hide();
}

var openModel = function() {
	$('#edit-modal').addClass('show');
	$('#edit-modal').show();
}

var closeViewModel = function(modelId="") {
	$(`#${modelId}`).removeClass('show');
	$(`#${modelId}`).hide();
}

var openViewModel = function(modelId="") {
	$(`#${modelId}`).addClass('show');
	$(`#${modelId}`).show();
}


var getEditInfo = function () {
	let kind_dict = {
		'0': '纸箱',
		'1': '木箱',
		'2': '托盘',
		'-1': '其他'
	}
	let kind = $('#edit-good-type').val();
	let length = $('#edit-good-length').val();
	let width = $('#edit-good-width').val();
	let height = $('#edit-good-height').val();
	let weight = $('#edit-good-weight').val();
	let num = $('#edit-good-number').val();
	
	if (parseInt(kind) === 3) {
		return {
			kind: "盘具",
			size: `(${length},${width})`,
			weight: weight,
			num: parseInt(num),
			heavyFoamRatio: parseFloat($('#heavy-foam-ratio-value').text())
		}; 
	}
	return {
		kind: kind_dict[parseInt(kind)],
		size: `(${length},${width},${height})`,
		weight: weight,
		num: parseInt(num),
		heavyFoamRatio: parseFloat($('#heavy-foam-ratio-value').text())
	};
}


var addEventForDelete = function () {
	
	$('.goods-delete').click(function () {
		// 找到父级tr节点
		let tr = $(this).parents('tr');
		tr.remove();
	});
	
}


var getTrInfo = function (editBtn) {
	
	let kind_dict = {
		'纸箱': '0',
		'木箱': '1',
		'托盘': '2',
		'盘具': '3',
		'其他': '-1'
	};
	
	let result = {};
	
	let tr = editBtn.parents('tr');
	editTr = tr;
	let td = tr.find('td');
	td.each(function (idx, dom) {
		if (idx === 0) {
			result['kind'] = kind_dict[$(dom).text()];
		}
		else if (idx === 1) {
			let size = $(dom).text();
			size = size.substring(1, size.length - 1);
			let length = parseInt(size.split(',')[0]);
			let width = parseInt(size.split(',')[1]);
			
			if (result['kind'] !== '3') {
				let height = parseInt(size.split(',')[2]);
				result['height'] = height;
			}
			result['width'] = width;
			result['length'] = length;
		}
		else if (idx === 2) {
			result['weight'] = parseFloat($(dom).text());
		}
		else if (idx === 3) {
			result['num'] = parseInt($(dom).text());
		}
	});
	return result;
}


var setTrInfo = function (info) {
	
	let kind_dict = {
		'0': '第一类',
		'1': '第二类',
		'2': '第三类',
		'-1': '其他'
	}
	
	let td = editTr.find('td');
	td.each(function (idx, dom) {
		if (idx === 0) {
			$(dom).html(kind_dict[info['kind']]);
		}
		else if (idx === 1) {
			$(dom).html(info['size']);
		}
		else if (idx === 2) {
			$(dom).html(info['weight']);
		}
		else if (idx === 3) {
			$(dom).html(info['num']);
		}
		else if (idx === 4) {
			let hfr = "";
			if (info['heavyFoamRatio'] >= 330) {
				hfr = `<span class="badge bg-primary-lt">重货</span>`;
			}else {
				hfr = `<span class="badge bg-secondary-lt">泡货</span>`;
			}
			$(dom).html(hfr);
		}
	});
}


var addEventForEdit = function () {
	
	$('.goods-edit').click(function() {
		
		// 1. 解绑模态框确定按钮的点击事件
		$('#edit-good-enter-btn').off('click');
		
		// 2. 获取当前项对应的货物信息
		let info = getTrInfo($(this));
		
		// 3. 初始化模态框数据
		$('#edit-good-length').val(info.length);
		$('#edit-good-width').val(info.width);
		$('#edit-good-weight').val(info.weight);
		$('#edit-good-type').val(info.kind);
		$('#edit-good-number').val(info.num);
		if (info.kind !== '3') {
			$('#height-col').show();
			$('#edit-label-length').text('长度');
			$('#edit-label-width').text('宽度');
			$('#edit-good-height').val(info.height);
		}
		else {
			$('#edit-label-length').text('半径');
			$('#edit-label-width').text('高');
			$('#height-col').hide();
		}
		$('#heavy-foam-ratio-text').html(refreshHeavyFoamRatio());
		
		// 4. 打开模态框
		openModel();
		
		// 5. 获取模态框编辑后数据
		$('#edit-good-enter-btn').click(function () {
			let edited_info = getEditInfo();
			console.log(edited_info);
			// 6. 更新表格数据
			setTrInfo(edited_info);
			// 7. 关闭模态框
			closeModel();
		});
		
	});
	
}


var addGood = function () {
	// 获取待添加货物信息
	let good_info = getEditInfo();
	console.log(good_info);
	
	let hfr = "";
	if (good_info['heavyFoamRatio'] >= 330) {
		hfr = `<span class="badge bg-primary-lt">重货</span>`;
	} else {
		hfr = `<span class="badge bg-secondary-lt">泡货</span>`;
	}
	
	$('#goods-table-body').append(`<tr>
										<td>${good_info['kind']}</td>
										<td>${good_info['size']}</td>
										<td>${good_info['weight']}</td>
										<td>${good_info['num']}</td>
										<td>${hfr}</td>
										<td><button class="btn btn-danger goods-delete" style="width:50px;height: 20px;">删除</button></td>
										<td><button class="btn btn-primary goods-edit" style="width:50px;height: 20px;">编辑</button></td>
									</tr>`);
	addEventForDelete();
	addEventForEdit();
	closeModel();
}


/**
 * 从表格获取所以货物信息
 */
var generateItems = function () {
	
	let results = [];
	
	// 获取table下的所有tr
	let trs = $('#goods-table-body').find('tr');
	trs.each(function (idx, trdom) {
		
		// 获取tr下所有的td
		let tds = $(trdom).find('td');
		
		let length = null, width = null, height = null, num = null, weight = null, shapeType = null, kind=null;
		tds.each(function (index, dom) {
			
			if (index === 0) {
				kind = $(dom).text();
			}
			else if (index === 1) {
				let size = $(dom).text();
				size = size.substring(1, size.length - 1);
				length = parseFloat(size.split(',')[0]);
				width = parseFloat(size.split(',')[1]);
				height = parseFloat(size.split(',')[2]);
				if (size.split(',').length === 2) {
					// 此时为圆柱体，type为0
					shapeType = 0;
					height = Math.PI * length;
				}
				else {
					// 此时为长方体，木箱为1，托盘为2，纸箱为3
					let kind_dict = {
						"木箱": 1,
						"托盘": 2,
						"纸箱": 3,
						"盘具": 0
					}
					shapeType = kind_dict[kind];
				}
			}
			else if (index === 2) {
				weight = parseFloat($(dom).text());
			}
			else if (index === 3) {
				num = parseInt($(dom).text());
			}
		});
		
		results.push([length, width, height, weight, num, shapeType]);
		
	});
	
	return results;
}


var refreshHeavyFoamRatio = function () {
	
	// 获取尺寸信息
	let length = $('#edit-good-length').val();
	let width = $('#edit-good-width').val();
	let height = $('#edit-good-height').val();
	
	// 获取重量
	let weight = $('#edit-good-weight').val();
	
	// 获取货物类型
	let type = $('#edit-good-type').val();
	
	let v = 0;	// 体积
	if (type !== '3') {
		// 长方体
		v = length * width * height;
	}
	else {
		// 圆柱体
		let r = length;
		let h = width;
		v = Math.PI * r * r * h;
	}
	
	// 计算重泡比
	let ret = (weight / v * 1000).toFixed(2);
	let threshold = parseFloat($("#weight-foam-rate").val());
	if (ret >= threshold) {
		return `<span id="heavy-foam-ratio-value">${ret}</span>&nbsp&nbsp<span class="badge bg-primary-lt">重货</span>`;
	}
	return `<span id="heavy-foam-ratio-value">${ret}</span>&nbsp&nbsp<span class="badge bg-secondary-lt">泡货</span>`;
	
};


var getAllRoute = function () {
	
	$.ajax({
		type: "POST",
		url: serverHost + "all_route",
		contentType: "application/json",
		dataType: "json",
		data: JSON.stringify({}),
		async: true,
		success: function(result) {
			all_routes = result;
			// console.log(result);
			let sHtml = "";
			for (let name in result) {
				sHtml += `<option value="${name}">${name}</option>`;
			}
			$('#route-select').html(sHtml);
			$('#enter-btn').trigger('click');
		}
	});
	
}


var generateCSV = function (header=true) {
	let result = "线路,单价,承重,车厢长,车厢宽,车厢高\n";
	if (header === false) {
		result = "";
	}
	for (let name in all_routes) {
		for (let car of all_routes[name]) {
			let loadbear = car.loadbear;
			let price = car.price;
			let width = car.size[0];
			let height = car.size[1];
			let depth = car.size[2];
			result += `${name},${price},${loadbear},${width},${height},${depth}\n`;
		}
	}
	return result;
}


$(document).ready(function () {
	
	closeModel();
	
	// 为模态框中的input绑定事件
	$('#edit-good-type').change(function () {
		let good_kind = parseInt($(this).val());
		
		if (good_kind === 3) {
			$('#height-col').hide();
			$('#edit-label-length').text('半径');
			$('#edit-label-width').text('高');
			$('#edit-good-length').val(5);
			$('#edit-good-width').val(10);
			$('#edit-good-weight').val(800);
		}
		
		else if (good_kind === -1) {
			$('#height-col').show();
			$('#edit-label-length').text('长度');
			$('#edit-label-width').text('宽度');
			$('#edit-good-length').val(1);
			$('#edit-good-width').val(1);
			$('#edit-good-height').val(1);
			$('#edit-good-weight').val(1);
		}
		else {
			$('#height-col').show();
			$('#edit-label-length').text('长度');
			$('#edit-label-width').text('宽度');
			$('#edit-good-length').val(good_size[good_kind][0]);
			$('#edit-good-width').val(good_size[good_kind][1]);
			$('#edit-good-height').val(good_size[good_kind][2]);
			$('#edit-good-weight').val(good_weight[good_kind]);
		}
		
	});
	
	// 为模态框中的关闭按钮绑定事件
	$('#edit-good-close-btn').click(function () {
		// 关闭模态框
		closeModel();
	});
	
	// 添加货物
	$('#add-good-btn').click(function () {
		
		// console.log(refreshHeavyFoamRatio());
		$('#heavy-foam-ratio-text').html(refreshHeavyFoamRatio());
		
		// 打开模态框
		openModel();
		
		// 解绑模态框确定按钮的所有点击事件
		$('#edit-good-enter-btn').off('click');
		
		// 为模态框确定按钮绑定事件
		$('#edit-good-enter-btn').click(function () {
			addGood();
		});
		$('#edit-good-cancel-btn').click(function () {
			closeModel();
		});
		
	});
	
	$('#enter-btn').click(function () {
		let items = generateItems();
		
		if (items.length > 0) {
			console.log({"items": items, "config_dict": config_dict});
			// 请求装车结果
			pack(items);
		}
		
	});
	
	$('#celar-btn').click(function () {
		
		$('#goods-table-body').empty();
		
	});
	
	addEventForDelete();
	addEventForEdit();
	
	// 设置界面
	initConfigModal();  // 初始化模态框的属性和事件
	$('#setting-btn').click(function(){
		$("#modal-config").show();
	});
	
	
	// 改变尺寸或重量信息时，应更新重泡比信息
	$('.heavy-foam-ratio-item').change(function () {
		
		$('#heavy-foam-ratio-text').html(refreshHeavyFoamRatio());
		
	});
	
	// 获取所有线路
	getAllRoute();
	
	$('#svg-export').click(function () {
		
		let csvContent = generateCSV();
		
		// 创建a标签
		var link = document.createElement("a");
		link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csvContent));
		link.setAttribute("download", "data.csv");
		document.body.appendChild(link);
		
		// 模拟点击下载
	    link.click();

	    // 移除虚拟的a标签
	    document.body.removeChild(link);
		
	});
	
	$('#svg-import').click(function () {
		
		// 模拟点击
		$('#file-upload').trigger('click');
		
	});
	
	$('#file-upload').on('change', function () {
		
		let file = document.getElementById('file-upload').files[0];
		let fileName = file.name;
		let nameArray = fileName.split('.');
		let fileType = nameArray[nameArray.length - 1];	// 获取文件后缀名
		let excelEnds = ['xls', 'xlsx', 'xlsm'];
		
		if (excelEnds.includes(fileType)) {
			// 用户上传了excel文件，需要传入后端进行解析
			let formData = new FormData();
			formData.append('file', $('#file-upload').prop('files')[0]);
			$.ajax({
				type: 'POST',
				url: serverHost + "parse_cars_info",
				data: formData,
				cache: false,
				processData: false,
				contentType: false,
				success: function(result) {
					console.log(result);
				}
			});
		}
		else if (fileType === 'csv' && file) {
			let reader = new FileReader();
			reader.onload = function(e) {
				let contents = e.target.result;
				let splitter = '';
				if (contents.includes('\n')) {
					splitter = '\n';
				}
				else if (contents.includes('\r')) {
					splitter = '\r';
				}
				else if (contents.includes('\t')) {
					splitter = '\t';
				}
				contents = contents.split(splitter);
				let idx = 0;
				let routes = {};
				for (let line of contents) {
					if (idx === 0) {
						idx ++;
						continue;
					}
					// 重设线路信息
					let tuple = line.split(',');
					let name = tuple[0];
					if (name === '') {
						idx ++;
						continue;
					}
					let price = parseFloat(tuple[1]);
					let loadbear = parseFloat(tuple[2]);
					let width = parseFloat(tuple[3]);
					let height = parseFloat(tuple[4]);
					let depth = parseFloat(tuple[5]);
					
					if (name in routes) {
						routes[name].push({size: [width, height, depth], loadbear: loadbear, price: price});
					} else {
						routes[name] = [{size: [width, height, depth], loadbear: loadbear, price: price}];
					}
					
					idx ++;
				}
				let sHtml = "";
				for (let name in routes) {
					sHtml += `<option value="${name}">${name}</option>`;
				}
				$('#route-select').html(sHtml);
				all_routes = routes;
			};
			reader.readAsText(file);
		}
		
	});
	
	$('#svg-view').on('click', function () {
		
		// 展示所有的路线、车辆信息
		let bodyHtml = "";
		for (let name in all_routes) {
			let current_name = $('#route-select').val();
			if (name !== current_name) {
				continue;
			}
			
			for (let car of all_routes[name]) {
				bodyHtml += `<tr>
								<td>${name}</td>
								<td>${car['size'][0]}</td>
								<td>${car['size'][1]}</td>
								<td>${car['size'][2]}</td>
								<td>${car['price']}</td>
								<td>${car['loadbear']}</td>
							</tr>`;
			}
		}
		$('#view-route-tablebody').html(bodyHtml);
		openViewModel("view-modal");
	});
	
	$('#view-close-btn').on('click', function () {
		closeViewModel("view-modal");
	});
	$('#view-cancel-btn').on('click', function () {
		closeViewModel("view-modal");
	});
	$('#view-enter-btn').on('click', function () {
		closeViewModel("view-modal");
	});
	
	// 点击导入货物按钮，触发input点击事件
	$('#svg-goods-import').on('click', function () {
		$('#file-goods-upload').trigger('click');
	});
	
	//  上传货物信息文件后，更新页面
	$('#file-goods-upload').on('change', function () {
		let file = document.getElementById('file-goods-upload').files[0];
		let kindMap = {
			'盘货': 0,
			'木箱': 1,
			'托盘': 2,
			'纸箱': 3
		}
		
		let fileName = file.name;
		let nameArray = fileName.split('.');
		let fileType = nameArray[nameArray.length - 1];	// 获取文件后缀名
		let excelEnds = ['xls', 'xlsx', 'xlsm'];
		
		if (excelEnds.includes(fileType)) {
			
			// excel表格类型文件，传入后端进行解析
			let formData = new FormData();
			formData.append('file', $('#file-goods-upload').prop('files')[0]);
			$.ajax({
				type: 'POST',
				url: serverHost + "parse_goods_info",
				data: formData,
				cache: false,
				processData: false,
				contentType: false,
				success: function(result) {
					console.log(result);
				}
			});
		}
		else if (fileType === 'csv' && file) {
			let reader = new FileReader();
			reader.onload = function(e) {
				let contents = e.target.result;
				let splitter = '\n';
				if (contents.includes('\n')) {
					splitter = '\n';
				}
				else if (contents.includes('\r')) {
					splitter = '\r';
				}
				else if (contents.includes('\t')) {
					splitter = '\t';
				}
				contents = contents.split(splitter);
				
				// 更新页面
				let bodyHtml = "";
				for (let item of contents) {
					
					if (item === '') {
						continue;
					}
					
					let tuple = item.split(',');
					let kind = kindMap[tuple[0]];
					if (kind === 0) {
						// 圆柱体
						let radius = parseFloat(tuple[1]);
						let height = parseFloat(tuple[2]);
						let weight = parseFloat(tuple[3]);
						let num = parseInt(tuple[4]);
						let v = Math.PI * radius * radius * height;
						let wvr = weight / v * 1000;
						let color = wvr > 330 ? "primary" : "secondary";
						bodyHtml += `<tr>
										<td>${tuple[0]}</td>
										<td>(${radius},${height})</td>
										<td>${weight}</td>
										<td>${num}</td>
										<td><span class="badge bg-${color}-lt">${wvr > 330 ? "重货" : "泡货"}</span></td>
										<td><button class="btn btn-danger goods-delete" style="width:50px;height: 20px;">删除</button></td>
										<td><button class="btn btn-primary goods-edit" style="width:50px;height: 20px;">编辑</button></td>
									</tr>`;
					} else {
						// 立方体
						let width = parseFloat(tuple[1]);
						let height = parseFloat(tuple[2]);
						let depth = parseFloat(tuple[3]);
						let weight = parseFloat(tuple[4]);
						let num = parseInt(tuple[5]);
						let v = width * height * depth;
						let wvr = weight / v * 1000;
						let color = wvr > 330 ? "primary" : "secondary";
						bodyHtml += `<tr>
										<td>${tuple[0]}</td>
										<td>(${width},${height},${depth})</td>
										<td>${weight}</td>
										<td>${num}</td>
										<td><span class="badge bg-${color}-lt">${wvr > 330 ? "重货" : "泡货"}</span></td>
										<td><button class="btn btn-danger goods-delete" style="width:50px;height: 20px;">删除</button></td>
										<td><button class="btn btn-primary goods-edit" style="width:50px;height: 20px;">编辑</button></td>
									</tr>`;
					}
				}
				$('#goods-table-body').html(bodyHtml);
				addEventForDelete();
				addEventForEdit();
				
			};
			reader.readAsText(file);
		}
	
	
	});
	
	
});


var showCheckList = function () {
	$('#div-checklist').html(`<div class="list">
										<span><input style="width: 20px; height: 20px;" class="item check-item" type="checkbox"><span style="font-size: 20px; padding-left: 7px;">木箱受力分析</span></span><br><br>
										<span><input style="width: 20px; height: 20px;" class="item check-item" type="checkbox"><span style="font-size: 20px; padding-left: 7px;">纸箱受力分析</span></span><br><br>
										<span><input style="width: 20px; height: 20px;" class="item check-item" type="checkbox"><span style="font-size: 20px; padding-left: 7px;">托盘受力分析</span></span><br><br>
										<span><input style="width: 20px; height: 20px;" class="item check-item" type="checkbox"><span style="font-size: 20px; padding-left: 7px;">盘货受力分析</span></span><br><br>
										<span><input style="width: 20px; height: 20px;" class="item check-item" type="checkbox"><span style="font-size: 20px; padding-left: 7px;">重货装箱自检</span></span><br><br>
										<span><input style="width: 20px; height: 20px;" class="item check-item" type="checkbox"><span style="font-size: 20px; padding-left: 7px;">泡货装箱自检</span></span>
									</div>`);
	// openViewModel('check-modal');
	
	let index = 0;
	let inter = setInterval(function () {
		$('#div-checklist').show();
		if (index >= 6) {
			clearInterval(inter);
			$('#div-checklist').hide();
		}
		$('.check-item').each(function (idx, ele) {
			if (idx === index) {
				$(ele).trigger('click');
			}
		})
		++ index;
	}, 500)
}


/**
 * 初始化Modal中的事件
 */
function initConfigModal() {
	var configModal = $("#modal-config");

	// 纸箱的配置项参数
	var paperBox = configModal.find("#tabs-paperBox-3");

	// 托盘的配置项参数
	var tray = configModal.find("#tabs-tray-3");
	tray.find("input[name='tray_area']").on("change", function(){
		var value = tray.find("input[name='tray_area']").val();
		tray.find("input[name='tray_area']").next().html(`单个托盘长*宽 &gt; ${value}m<sup>2</sup> 可堆叠`);
	});
	tray.find("input[name='tray_weight_max']").on("change", function(){
		var value = tray.find("input[name='tray_weight_max']").val();
		tray.find("input[name='tray_weight_max']").next().html(`单个托盘重量&lt; ${value}kg 可堆叠`);
	});
	tray.find("input[name='tray_weight_min']").on("change", function(){
		var value = tray.find("input[name='tray_weight_min']").val();
		tray.find("input[name='tray_weight_min']").next().html(`单个托盘重量≤ ${value}kg 不能被堆叠`);
	});
	tray.find("input[name='total_weight']").on("change", function(){
		var value = tray.find("input[name='total_weight']").val();
		tray.find("input[name='total_weight']").next().html(`堆叠层的总重量 ≤ min(最下层单个托盘的重量, ${value}kg)`);
	});
	tray.find("input[name='tray_area']").trigger("change");
	tray.find("input[name='tray_weight_max']").trigger("change");
	tray.find("input[name='tray_weight_min']").trigger("change");
	tray.find("input[name='total_weight']").trigger("change");

	// 木箱的配置项参数
	var woodenBox = configModal.find("#tabs-woodenBox-3");
	woodenBox.find("input[name='box_weight']").on("change", function(){
		var value = woodenBox.find("input[name='box_weight']").val();
		woodenBox.find("input[name='box_weight']").next().html(`≤${value}kg 的木箱不能被堆叠`);
	});
	woodenBox.find("input[name='third_box_weight']").on("change", function(){
		var value1 = woodenBox.find("input[name='third_box_weight']").val();
		var value2 = woodenBox.find("input[name='second_box_weight_1']").val();
		if (value1 != value2){
			woodenBox.find("input[name='second_box_weight_1']").val(value1);
		}
	});
	woodenBox.find("input[name='second_box_weight_1']").on("change", function(){
		var value1 = woodenBox.find("input[name='third_box_weight']").val();
		var value2 = woodenBox.find("input[name='second_box_weight_1']").val();
		if (value1 != value2){
			woodenBox.find("input[name='third_box_weight']").val(value2);
		}
	});
	woodenBox.find("input[name='total_weight']").on("change", function(){
		var value = woodenBox.find("input[name='total_weight']").val();
		woodenBox.find("input[name='total_weight']").next().html(`堆叠层的总重量 ≤ min(最下层单个托盘的重量, ${value}kg)`);
	});
	woodenBox.find("input[name='box_weight']").trigger("change");
	woodenBox.find("input[name='total_weight']").trigger("change");


	// 盘具配置项的参数联动事件
	var dish = configModal.find("#tabs-dish-3");
	dish.find("input[name='dish_radius']").on("change", function(){
		var value = dish.find("input[name='dish_radius']").val();
		dish.find("input[name='dish_radius']").next().html(`盘径 ≤ ${value}mm 可堆叠`);
	});
	dish.find("input[name='third_dish_radius']").on("change", function(){
		var value1 = dish.find("input[name='third_dish_radius']").val();
		var value2 = dish.find("input[name='second_dish_radius_1']").val();
		if (value1 != value2){
			dish.find("input[name='second_dish_radius_1']").val(value1);
		}
	});
	dish.find("input[name='second_dish_radius_1']").on("change", function(){
		var value1 = dish.find("input[name='third_dish_radius']").val();
		var value2 = dish.find("input[name='second_dish_radius_1']").val();
		if (value1 != value2){
			dish.find("input[name='third_dish_radius']").val(value2);
		}
	});
	dish.find("input[name='second_dish_radius_2']").on("change", function(){
		var value1 = dish.find("input[name='second_dish_radius_2']").val();
		var value2 = dish.find("input[name='first_dish_radius']").val();
		if (value1 != value2){
			dish.find("input[name='first_dish_radius']").val(value1);
		}
	});
	dish.find("input[name='first_dish_radius']").on("change", function(){
		var value1 = dish.find("input[name='second_dish_radius_2']").val();
		var value2 = dish.find("input[name='first_dish_radius']").val();
		if (value1 != value2){
			dish.find("input[name='second_dish_radius_2']").val(value2);
		}
	});

	dish.find("input[name='dish_radius']").trigger("change");

	// 通用配置项中的顺序联动事件
	var general = configModal.find("#tabs-general-3");
	
	// ======  按钮的事件 ======

	// 关闭 modal 框
	configModal.find(".btn-close").on("click", function () {
		configModal.hide();
	});

	// 恢复默认值
	configModal.find("#reset").on("click", function(){
		// 纸箱的配置项参数
		var paperBox = configModal.find("#tabs-paperBox-3");
		paperBox.find("input[name='weight_foam_rate']").val(330);
		paperBox.find("input[name='volume_rate']").val(90);

		// 托盘的配置项参数
		var tray = configModal.find("#tabs-tray-3");
		tray.find("input[name='weight_foam_rate']").val(330);
		tray.find("input[name='tray_area']").val(0.6);
		tray.find("input[name='tray_weight_max']").val(600);
		tray.find("input[name='tray_weight_min']").val(100);
		tray.find("input[name='total_weight']").val(600);
		
		// 木箱的配置项参数
		var woodenBox = configModal.find("#tabs-woodenBox-3");
		woodenBox.find("input[name='weight_foam_rate']").val(330);
		woodenBox.find("input[name='box_weight']").val(60);
		woodenBox.find("input[name='third_box_weight']").val(600);
		woodenBox.find("input[name='second_box_weight_1']").val(600);
		woodenBox.find("input[name='second_box_weight_2']").val(1200);
		woodenBox.find("input[name='total_weight']").val(1200);


		// 盘具配置项的参数联动事件
		var dish = configModal.find("#tabs-dish-3");
		dish.find("input[name='weight_foam_rate']").val(330);
		dish.find("input[name='dish_radius']").val(1350);
		dish.find("input[name='third_dish_radius']").val(750);
		dish.find("input[name='second_dish_radius_1']").val(750);
		dish.find("input[name='second_dish_radius_2']").val(1350);
		dish.find("input[name='first_dish_radius']").val(1350);

		// 通用配置项中的顺序联动事件
		var general = configModal.find("#tabs-general-3");
		general.find("input[name='weight_foam_rate']").val(330);
	});

	// 确认按钮
	configModal.find("#confirm").on("click", function(){
		// 纸箱的配置项参数
		var paperBox = configModal.find("#tabs-paperBox-3");
		config_dict["paperBox"] = {"weight_foam_rate": paperBox.find("input[name='weight_foam_rate']").val(), 
								   "volume_rate": paperBox.find("input[name='volume_rate']").val()
								}

		// 托盘的配置项参数
		var tray = configModal.find("#tabs-tray-3");
		config_dict["tray"] = {"weight_foam_rate": tray.find("input[name='weight_foam_rate']").val(), 
							   "tray_area": tray.find("input[name='tray_area']").val(), 
								"tray_weight_max":tray.find("input[name='tray_weight_max']").val(), 
								"tray_weight_min":tray.find("input[name='tray_weight_min']").val(), 
								"total_weight":tray.find("input[name='total_weight']").val()
							}
		
		// 木箱的配置项参数
		var woodenBox = configModal.find("#tabs-woodenBox-3");
		config_dict["woodenBox"] = { "weight_foam_rate": woodenBox.find("input[name='weight_foam_rate']").val(),
								"box_weight": woodenBox.find("input[name='box_weight']").val(),
								"third_box_weight": woodenBox.find("input[name='third_box_weight']").val(),
								"second_box_weight_1": woodenBox.find("input[name='second_box_weight_1']").val(),
								"second_box_weight_2": woodenBox.find("input[name='second_box_weight_2']").val(),
								"total_weight": woodenBox.find("input[name='total_weight']").val()
							}


		// 盘具配置项的参数联动事件
		var dish = configModal.find("#tabs-dish-3");
		config_dict["dish"] = { "weight_foam_rate": dish.find("input[name='weight_foam_rate']").val(),
								"dish_radius": dish.find("input[name='dish_radius']").val(),
								"third_dish_radius": dish.find("input[name='third_dish_radius']").val(),
								"second_dish_radius_1": dish.find("input[name='second_dish_radius_1']").val(),
								"second_dish_radius_2": dish.find("input[name='second_dish_radius_2']").val(),
								"first_dish_radius": dish.find("input[name='first_dish_radius']").val()
							}

		// 通用配置项中的顺序联动事件
		var general = configModal.find("#tabs-general-3");
		config_dict["general"] = { 	"weight_foam_rate": general.find("input[name='weight_foam_rate']").val(),
								  	"stack_sequence": general.find("select[name='stack_sequence']").val()
								}

		// Modal框隐藏
		configModal.hide();

	});
	configModal.find("#confirm").trigger("click"); // 获取初始化参数
}

